<?php
namespace app\admin\controller;
header("Content-Type: text/html;charset=utf-8");
use think\Request;
use think\Db;

class goods extends Common
{
    //商品列表
    public function index()
    {
        //分页处理
        $list = db('goods')->alias('a')->join('goods_guigetype c','a.id=c.goods_id')->join('goods_attributes d','c.id=d.guigeType_id')->field('a.*,c.name as guigeType_name,c.pid,d.id as attributes_id,d.price,d.sale,d.kucun,d.jifen,d.is_onsale')->order('d.id desc')->paginate(5);
        $color_list = db('goods_guigetype')->select();
        //对象转数组
        $data = $list->all();
        foreach($data as $k1 => $v1){
            foreach ($color_list as $k2 => $v2){
                if($v1['pid']==$v2['id']){
                    $data[$k1]['guigeType_name']=[
                        'father'=>$v2['name'],          //1级规格名字
                        'son'=>$data[$k1]['guigeType_name']     //2级规格名字
                    ];
                }
            }           
        }
        //合并数组为字符串
        foreach($data as $k1 => $v1){
            foreach ($data as $k2 => $v2) {
                if(is_array($v2['guigeType_name'])){
                    //数组转字符串
                    $guigeType_name = implode(' , ',$data[$k2]['guigeType_name']);
                    $data[$k2]['guigeType_name'] = $guigeType_name;
                }
            }
            $data[$k1]['price'] = number_format((float)$v1['price'],2);
        }
        //只取商品图片的第一张
        $row=[];
        foreach( $data as $val )
        {
            $img = json_decode($val['src'],true);    //转换格式,json字符串->php数组
            if($img!=NULL){
                $val['src']=array($img[0]);
            }else{
                $val['src']=array($val['src']);
            }
            $thumb_img = json_decode($val['thumb_src'],true);    //转换格式,json字符串->php数组
            if($thumb_img!=NULL){
                $val['thumb_src']=array($img[0]);
            }else{
                $val['thumb_src']=array($val['thumb_src']);
            }
            $row[] = $val;  //存入新数组$row中
        }
        $page = $list->render();
        $page = str_replace([
            'pagination',
            'disabled',
            'active'
        ],[
            'am-pagination tpl-pagination',
            'am-disabled',
            'am-active'
        ],$page);
        $status = [
            "0" => '未上架',
            "1" => '已上架',
        ];
        // dump($row);die;
        $this->assign('status',$status);
        $this->assign('list',$row);
        $this->assign('page',$page);
        return view();
    }
    //点击按钮改变商品已上架或未上架状态
    public function get_onsale($attributes_id){

        $ret = db('goods_attributes')->where("id='$attributes_id'")->find();
        if($ret['is_onsale']==1){
            db('goods_attributes')->where("id='$attributes_id'")->update(['is_onsale' => '0']);
        }else{
            db('goods_attributes')->where("id='$attributes_id'")->update(['is_onsale' => '1']);
        }
        $ret = db('goods_attributes')->where("id='$attributes_id'")->find();
        return $ret['is_onsale'];
    }
    //添加商品页面
    public function addGoods()
    {

        $fenlei_list = db('goods_fenlei')->where("grade='1'")->select();
        $fenlei_son_list = db('goods_fenlei')->where("grade='2' and pid={$fenlei_list[0]['id']}")->select();
        if($fenlei_son_list){
            $this->assign('son_list',$fenlei_son_list);
        }
        session('fenlei_list',$fenlei_list);
        $this->assign('list',$fenlei_list);
        return view('addGoods');
    }
    //添加商品(数据库)
    public function insertGoods(){
        $data = input('post.');
        $data['src'] = json_encode($data['src']);
        $data['thumb_src'] = json_encode($data['thumb_src']);
        if($data['fenlei_son_id']){
            $data['fenlei_id']=$data['fenlei_son_id'];
            unset($data['fenlei_son_id']);
        }else{
            unset($data['fenlei_son_id']);
        }
        $ret = Db::name('goods')->insert($data);
        $goodId = Db::name('goods')->getLastInsID();
        if($ret){
            session('goodId',$goodId);
            session('goodName',$data['name']);
            $this->success('新增商品成功!','admin/goods/addGuige');
        }else{
            $this->error('添加失败');
        }
    }
    //添加商品规格页面  
    public function addGuige()
    {
        $goods_list = db('goods')->select();
        // dump($goods_list);die;
        $this->assign('goods_list',$goods_list);
        return view('addGuige');
    }
    //添加商品规格(数据库)
    public function insertGuige(){
        $post_list = input('post.');
        // dump(count($data['guigeType_name']));die;
        $guige_data = [
            'name' => $post_list['name'],
            'pid' => 0,
            'goods_id' => $post_list['goods_id'],
        ];
        $res = db('goods_guige')->where("goods_id={$post_list['goods_id']} and name='{$post_list['name']}'")->find();
        if($res){
            $guige_id = $res['id'];
        }else{
            //获取规格id
            $ret = Db::name('goods_guige')->insert($guige_data);
            $guige_id = Db::name('goods_guige')->getLastInsID();
        } 
        //保存规格属性名称
        $guigeType_name_list = [];
        for($i=0;$i<count($post_list['guigeType_name']);$i++){
            if($post_list['guigeType_name'][$i]!=''){
                $guigeType_name_list[] = $post_list['guigeType_name'][$i];
            }
        }
        //遍历入库规格属性
        for($i=0;$i<count($guigeType_name_list);$i++){
            $guigeType_data = [
                'name' => $guigeType_name_list[$i],
                'pid' => 0,
                'goods_id' => $post_list['goods_id'],
                'guige_id' => $guige_id,
            ];
            Db::name('goods_guigetype')->insert($guigeType_data);
        }
        $this->success('新增商品规格成功!','admin/goods/addGuigeSon');
    }
    //添加商品子规格页面  
    public function addGuigeSon()
    {
        $goods_list = db('goods')->order('id asc')->select();
        $goods_guige_list = db('goods_guigetype')->where("goods_id={$goods_list[0]['id']} and pid=0")->select();
        $this->assign('goods_guige_list',$goods_guige_list);
        $this->assign('goods_list',$goods_list);
        return view('addGuigeSon');
    }
    //添加商品子规格属性(数据库)
    public function insertGuigeSon(){
        $post_list = input('post.');
        $guige_list = db('goods_guigetype')->where("id={$post_list['guigeType_id']}")->find();
        $guige_fa_id = $guige_list['guige_id'];

        $guige_data = [
            'name' => $post_list['name'],
            'pid' => $guige_fa_id,
            'goods_id' => $post_list['goods_id'],
        ];
        //获取规格id
        $ret = Db::name('goods_guige')->insert($guige_data);
        $guige_id = Db::name('goods_guige')->getLastInsID();
        //保存规格属性名称
        $guigeType_name_list = [];
        for($i=0;$i<count($post_list['guigeType_name']);$i++){
            if($post_list['guigeType_name'][$i]!=''){
                $guigeType_name_list[] = $post_list['guigeType_name'][$i];
            }
        }
        //遍历入库规格属性
        for($i=0;$i<count($guigeType_name_list);$i++){
            $guigeType_data = [
                'name' => $guigeType_name_list[$i],
                'pid' => $post_list['guigeType_id'],
                'goods_id' => $post_list['goods_id'],
                'guige_id' => $guige_id,
            ];
            Db::name('goods_guigetype')->insert($guigeType_data);
        }
        $this->success('新增商品子规格成功!');
    }
    //添加商品固定属性页面 
    public function addAttributes()
    {
        $goods_list = db('goods')->order('id asc')->select();
        $this->assign('goods_list',$goods_list);
        return view('addAttributes');
    }
    //添加商品固定属性(数据库)
    public function insertAttributes(){
        $post_list = input('post.');
        // dump($post_list);die;
        //遍历入库规格属性
        for($i=0;$i<count($post_list['guigeType_id']);$i++){
            $attributes_data = [
                'price' => $post_list['price'][$i],
                'sale' => 0,
                'jifen' => $post_list['jifen'][$i],
                'kucun' => $post_list['kucun'][$i],
                'goods_id' => $post_list['goods_id'],
                'guigeType_id' => $post_list['guigeType_id'][$i],
            ];
            if(empty($post_list['price'][$i]) || empty($post_list['jifen'][$i]) || empty($post_list['kucun'][$i])){
                $this->error('还有商品未入库!');
            }
            Db::name('goods_attributes')->insert($attributes_data);
            
        }
        $price_list = [];
        $ret = db('goods_attributes')->where("goods_id={$post_list['goods_id']}")->select();
        foreach ($ret as $k => $v) {
            $price_list[] = $v['price'];
        }
        $min_price = min($price_list);
        db('goods')->where("id={$post_list['goods_id']}")->setField('min_price',"{$min_price}");
        $this->success('添加商品成功!','admin/goods/index');
    }
    //上传图片
    public function upimg()
    {
        $file = request()->file('img');
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息
                $img = '/uploads/'.$info->getSaveName();
                // echo $img;
                //制作略缩图
                $image = \think\Image::open('.'.$img);
                $date = date('Ymd',time());
                $path = "uploads/thumbs/$date";
                if(!file_exists($path)){
                    mkdir($path,0777,true);
                }
                $result = $image->thumb(150,100)->save('.'.'/uploads/thumbs/'.$info->getSaveName());
                $img_thumb = '/uploads/thumbs/'.$info->getSaveName();
                return ['img'=>$img,'img_thumb'=>$img_thumb];
            }else{
                // 上传失败获取错误信息
                $this->error($file->getError());
            }
        }
    }
    //Ajax根据商品分类获取二级分类数据
    public function get_sel($id){
        $list = db('goods_fenlei')->where("pid={$id}")->order('id asc')->select();
        print_r(json_encode($list));
    }
    //Ajax根据二级分类获取id
    public function getfenlei_Id($id){
        $list = db('goods_attributes')->where("guigeType_id={$guigeType_id}")->find();
        print_r(json_encode($list));
    }
    //Ajax根据商品名称获取商品规格名称
    public function get_guige($id){
        $list = db('goods_guigetype')->where("goods_id={$id} and pid=0")->select();
        print_r(json_encode($list));
    }
    //Ajax根据商品名称获取商品规格详情数据
    public function getGoodList($id){
        $goods_guigetype_list = db('goods_guigetype')->where("goods_id={$id}")->order('id asc')->select();
        $goods_attributes_list = db('goods_attributes')->where("goods_id={$id}")->order('id asc')->select();
        $temp_list = $goods_guigetype_list;

        foreach ($goods_guigetype_list as $k1 => $v1) {
            foreach ($goods_attributes_list as $k2 => $v2) {
                if($v2['guigeType_id']==$v1['id']){
                    unset($goods_guigetype_list[$k1]);
                }
            }
        }
        foreach ($goods_guigetype_list as $k1=>$v1){
            foreach ($goods_guigetype_list as $k2=>$v2){
                if($v2['pid']==$v1['id']){
                    $goods_guigetype_list[$k1]['son'][]=$v2;
                    unset($goods_guigetype_list[$k2]);
                }
            }
        }
        foreach ($goods_guigetype_list as $k1=>$v1){
            foreach ($temp_list as $k2=>$v2){
                if($v1['id']==$v2['pid'] && !isset($v1['son'])){
                    unset($goods_guigetype_list[$k1]);
                }
            }
        }        
        print_r(json_encode(array_values($goods_guigetype_list)));
    }
    //编辑修改商品固定属性(页面)
    public function good_edit(){
        $attributes_id=input('get.attributes_id');
        $result =  db('goods')->alias('a')->join('goods_guigetype c','a.id=c.goods_id')->join('goods_attributes d','c.id=d.guigeType_id')->field('a.*,c.name as guigeType_name,c.pid,d.id as attributes_id,d.price,d.sale,d.kucun,d.jifen,d.is_onsale')->where("d.id={$attributes_id}")->find();
        $img = json_decode($result['src'],true);    //转换格式,json字符串->php数组
        if($img!=NULL){
            $result['src']=$img;
        }else{
            $result['src']=array($result['src']);
        }
        $thumb_img = json_decode($result['thumb_src'],true);    //转换格式,json字符串->php数组
        if($thumb_img!=NULL){
            $result['thumb_src']=$thumb_img;
        }else{
            $result['thumb_src']=array($result['thumb_src']);
        }
        //重组数组,将thumb_src对应存入src数组中
        $row = [];
        foreach ($result['src'] as $k1 => $v1) {
            foreach ($result['thumb_src'] as $k2 => $v2) {
                if($k1==$k2){
                    $row[] = $v1.'--'.$v2;
                }                
            }            
        }
        $row2 = [];
        for($i=0;$i<count($row);$i++){
            $row2[]=explode('--',$row[$i]);
        }
        $result['src'] = $row2;
        unset($result['thumb_src']);
        // dump($result);die;
        $this->assign('result',$result);
        return view('edit');
    }
    //编辑修改商品固定属性(数据库)
    public function update()
    {
        $attributes_id=input('get.attributes_id');
        $goods_id = input('get.goods_id');
        $post_list=input('post.');
        // dump($post_list);die;
        $goods_data = [
            'name' => $post_list['name'],
            'src' => json_encode($post_list['src']),
            'thumb_src' => json_encode($post_list['thumb_src']),
            'abstract' => $post_list['abstract'],
        ];
        db('goods')->where("id={$goods_id}")->update($goods_data);
        $attributes_data = [
            'price' => $post_list['price'],
            'jifen' => $post_list['jifen'],
            'kucun' => $post_list['kucun'],
        ];
        $ret = db('goods_attributes')->where("id={$attributes_id}")->update($attributes_data);
        $price_list = [];
        $ret = db('goods_attributes')->where("goods_id={$goods_id}")->select();
        foreach ($ret as $k => $v) {
            $price_list[] = $v['price'];
        }
        $min_price = min($price_list);
        db('goods')->where("id={$goods_id}")->setField('min_price',"{$min_price}");
        $this->success('编辑修改成功','admin/goods/index');
    }
}